package top.lyjwn.todo.common.utils.http;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.wildfly.common.annotation.NotNull;
import top.lyjwn.todo.common.utils.EmptyUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class HttpClientLr {

    private Logger loggerHttpd = LoggerFactory.getLogger(getClass());

    private RequestConfig requestConfig;

    public void setRequestConfig(RequestConfig requestConfig) {
        this.requestConfig = requestConfig;
    }

    public void setLoggerHttpd(Logger loggerHttpd) {
        this.loggerHttpd = loggerHttpd;
    }

    private RequestConfig getRequestConfig() {
        // 构建默认超时配置
        if (this.requestConfig != null) {
            this.requestConfig = RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000)
                    .setSocketTimeout(15000)
                    .build();
        }
        return this.requestConfig;
    }

    private PoolingHttpClientConnectionManager cm;

    public PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(400); // 总连接数上限
            cm.setDefaultMaxPerRoute(100); // 单路由最大连接数
            cm.setValidateAfterInactivity(2000);
        }
        return cm;

    }

    public CloseableHttpClient getHttpClient() {
        return HttpClients.custom()
                .setConnectionManager(getPoolingHttpClientConnectionManager())
                .setConnectionManagerShared(true)
                .setDefaultRequestConfig(getRequestConfig())
                .build();
    }

    public String post(String url, Map<String, String> headers, Map<String, String> content) {
        try (CloseableHttpClient client = getHttpClient()) {
            loggerHttpd.info("[in param] : {}", content);
            HttpPost httpPost = getHttpPost(url, headers, content);
            // 发送请求并获取响应
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                // 获取响应状态码
                //int statusCode = response.getStatusLine().getStatusCode();

                // 获取响应体内容
                String responseContent = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                loggerHttpd.info("[out param] : {}", responseContent);
                return responseContent;

            } finally {

            }
        } catch (IOException e2) {
            loggerHttpd.error("连接异常: ", e2);
        }
        return null;
    }

    public String post(String url, String content) {
        return post(url, null, content);
    }

    public String post(String url, Map<String, String> headers, String content) {
        try (CloseableHttpClient client = getHttpClient()) {
            loggerHttpd.info("[in param] : {}", content);
            HttpPost httpPost = getHttpPost(url, headers, content);
            // 发送请求并获取响应
            try (CloseableHttpResponse response = client.execute(httpPost)) {
                // 获取响应状态码
                //int statusCode = response.getStatusLine().getStatusCode();

                // 获取响应体内容
                String responseContent = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                loggerHttpd.info("[out param] : {}", responseContent);
                return responseContent;

            } finally {

            }
        } catch (IOException e2) {
            loggerHttpd.error("连接异常: ", e2);
        }
        return null;
    }

    private @NotNull HttpPost getHttpPost(String url, Map<String, String> headers, Map<String, String> content) throws UnsupportedEncodingException {
        HttpPost httpPost = new HttpPost(url);
        if (EmptyUtil.isNotEmpty(headers)) {
            for (Map.Entry<String, String> stringStringEntry : headers.entrySet()) {
                httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        List<NameValuePair> params = new ArrayList<>();
        for (Map.Entry<String, String> stringStringEntry : content.entrySet()) {
            params.add(new BasicNameValuePair(stringStringEntry.getKey(), stringStringEntry.getValue()));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
        return httpPost;
    }


    private @NotNull HttpPost getHttpPost(String url, Map<String, String> headers, String content) {
        HttpPost httpPost = new HttpPost(url);
        if (EmptyUtil.isNotEmpty(headers)) {
            for (Map.Entry<String, String> stringStringEntry : headers.entrySet()) {
                httpPost.setHeader(stringStringEntry.getKey(), stringStringEntry.getValue());
            }
        }
        StringEntity entity = new StringEntity(content, StandardCharsets.UTF_8);
        httpPost.setEntity(entity);
        return httpPost;
    }
}
